﻿using CinemaMaestro.BusinessLayer.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using CinemaMaestro.WebApplication.Models;

namespace CinemaMaestro.WebApplication.Controllers
{
    public class CinemaController : Controller
    {
        // GET: Cinema
        public ActionResult Index(int id = 0)
        {
            if (id != 0)
            {
                var businessUoW = CinemaMaestro.Common.IocContainer.Resolver.Get<IBusinessObjectFactory>();
                var tomorrow = DateTime.Now.AddDays(1).Date;
                ViewBag.DateTime = DateTime.Now;
                var screeningModels = businessUoW.Screenings.Read().Where(cinema => cinema.Room.Cinema.Id == id).AsEnumerable().Where(cinema => cinema.StartDate > DateTime.Now && cinema.StartDate < tomorrow).OrderBy(x => x.StartDate);
                ViewBag.CinemaName = businessUoW.Cinemas.Read().Where(x => x.Id == id).FirstOrDefault().Name;
                ViewBag.CinemaId = id;
                var list = new List<ScreeningViewModels>();
                foreach (var screeningModel in screeningModels)
                {
                    ScreeningViewModels screeningViewModel = screeningModel;
                    var base64 = screeningModel.Movie.Image != null ? Convert.ToBase64String(screeningModel.Movie.Image) : string.Empty;
                    screeningViewModel.Movie.Image = String.Format("data:image/jpg;base64,{0}", base64);
                    list.Add(screeningViewModel);

                }
                return View(list);
            }
            else
            {
                return Redirect("/Home/Index");
            }
        }

        [HttpPost]
        public ActionResult Index()
        {
            var businessUoW = CinemaMaestro.Common.IocContainer.Resolver.Get<IBusinessObjectFactory>();

            var day = Convert.ToDateTime(Request["Date"]);
            ViewBag.DateTime = day;
            var cinemaId = Convert.ToInt32(Request["CinemaId"].ToString().Substring(1, Request["CinemaId"].ToString().Length-2).Split('=')[1]);
            var tomorrow = day.AddDays(1);
            var list = businessUoW.Screenings.Read().Where(x => x.Room.Cinema.Id == cinemaId).AsEnumerable().Where(x => x.StartDate > day && x.StartDate < tomorrow).OrderBy(x => x.StartDate);
            ViewBag.CinemaName = businessUoW.Cinemas.Read().Where(x => x.Id == cinemaId).FirstOrDefault().Name;
            ViewBag.CinemaId = cinemaId;
            List<ScreeningViewModels> models = new List<ScreeningViewModels>();

            foreach (var model in list)
            {
                ScreeningViewModels movie = model;
                var base64 = model.Movie.Image != null ? Convert.ToBase64String(model.Movie.Image) : string.Empty;
                movie.Movie.Image = String.Format("data:image/jpg;base64,{0}", base64);
                models.Add(movie);
            }
            return View(models);
        }

        public JsonResult GetLanguage(int screeningId)
        {
            var businessUoW = CinemaMaestro.Common.IocContainer.Resolver.Get<IBusinessObjectFactory>();

            var screening = businessUoW.Screenings.Read().FirstOrDefault(x => x.Id == screeningId);
            var capacity = screening.Room.Capacity;

            var reservedSeatCount = businessUoW.Reservations.Read()
                .Where(x => x.Screening.Id == screeningId)
                .Sum(x => x.TicketNr + x.DiscountTicketNr);

            var soldSeatCount = businessUoW.Sales.Read()
                .Where(x => x.Screening.Id == screeningId)
                .Sum(x => x.TicketNr + x.DiscountTicketNr);

            var availableTicket = capacity - soldSeatCount - reservedSeatCount;

            var list = businessUoW.Screenings.Read().Where(x => x.Id == screeningId).Select(x => new { LanguageId = x.Language.Id, LanguageName = x.Language.Name, Ticket = x.Price, DiscountedPrice = x.DiscountedPrice, AvailableTicket = availableTicket });
            return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        public JsonResult CreateReservation(int screeningId, int ticketNr, int discountedTicketNr, string name, string email, string telephone, string reservatedSeats)
        {
            var businessUoW = CinemaMaestro.Common.IocContainer.Resolver.Get<IBusinessObjectFactory>();

            var screening = businessUoW.Screenings.Read().AsNoTracking().First(x => x.Id == screeningId);

            var reservation = new ReservationViewModels();
            reservation.Screening = screening;
            reservation.TicketNr = ticketNr;
            reservation.DiscountTicketNr = discountedTicketNr;
            reservation.Name = name;
            reservation.Email = email;
            reservation.TelephoneNr = telephone;
            reservation.Seats = reservatedSeats.Substring(0, reservatedSeats.Length - 1);

            var result = businessUoW.Reservations.Create(reservation);

            return new JsonResult { Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        public JsonResult GetRoomSeats(int screeningId)
        {
            var businessUoW = CinemaMaestro.Common.IocContainer.Resolver.Get<IBusinessObjectFactory>();

            var screening = businessUoW.Screenings.Read().AsNoTracking().First(x => x.Id == screeningId);

            return new JsonResult { Data = screening.Room.Seats, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }
}